<?php

namespace app\common\service\user;

use app\admin\model\user\User;
use app\common\service\BaseService;
use app\validate\PhoneLogin;
use think\exception\ValidateException;

class LoginService extends BaseService
{
    /**
     * Author:Zhongyuan Lu
     * 手机号、密码 登录
     * @param $params
     * @return array
     */
    public static function PhoneLogin($params)
    {
        try {
            validate(PhoneLogin::class)->batch(true)->check($params);

        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::fail($e->getError());
        }

        //根据手机号查询用户信息
        $where['phone'] = $params['phone'];
        $userInfo = User::whereFind($where);
        $userInfo && $userInfo = $userInfo->toArray();

        if ($userInfo['password'] !== password($params['password'])) {
            return self::fail('密码错误');
        }

        unset($userInfo['password']);

        $data['last_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['last_time'] = time();
        User::updateOne($userInfo['id'],$data);
        //加密id  返回给前台
        $userInfo['id'] = encrypt($userInfo['id']);

        return self::success('登录成功',$userInfo);
    }

    /**
     * Author:Zhongyuan Lu
     * 用户注册
     * @param $params
     * @return array
     */
    public static function register($params)
    {
        //密码加密
        $params['password'] = password($params['password']);
        //判断是否是受推广而来的
        if (!empty($params['spread_code'])) {
            $userInfo = User::where('spread_code',$params['spread_code'])->find();
            $userInfo && $userInfo = $userInfo->toArray();
            $params['one_level_distributor'] = !empty($userInfo) ? $userInfo['id'] : 0;
            $params['two_level_distributor'] = $userInfo['one_level_distributor'] ?? 0;
            $params['three_level_distributor'] = $userInfo['two_level_distributor'] ?? 0;
        }

        //生成用户唯一邀请码
        while (1) {
            $params['spread_code'] = create_unique();
            $data = User::where('spread_code',$params['spread_code'])->find();
            if (empty($data)) {
                break;
            }
        }

        $id = User::createOne($params);

        if ($id) {
            return self::success( '注册成功');
        }
        return self::fail('注册失败');
    }
}